package org.androidpn.server.xmpp.packet;

import java.util.ArrayList;
import java.util.List;

import org.androidpn.server.entity.Friend;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;

/**
 * packet friendGroup
 * 
 * @author 蔡琪
 * 
 */
public class FriendPacket extends IQ {

	/**
	 * 好友 操作信息枚举
	 * 
	 * @author 蔡琪
	 * 
	 */
	public enum Operation {
		/** 通过nickname添加好友 */
		addFriendByNickname,
		/** 通过nickname删除好友 */
		deleteFriendByNickname
	}

	/** 角色ID */
	private Long roleID;

	/** 好友集合 */
	private List<Friend> friends = new ArrayList<Friend>();

	/** 好友信息 */
	private Friend friend;

	/**
	 * 好友分组id
	 */
	private Long friendGroupId;

	private Operation operation;

	public Long getRoleID() {
		return roleID;
	}

	public void setRoleID(Long roleID) {
		this.roleID = roleID;
	}

	public List<Friend> getFriends() {
		return friends;
	}

	public void setFriends(List<Friend> friends) {
		this.friends = friends;
	}

	public Friend getFriend() {
		return friend;
	}

	public Long getFriendGroupId() {
		return friendGroupId;
	}

	public void setFriendGroupId(Long friendGroupId) {
		this.friendGroupId = friendGroupId;
	}

	public void setFriend(Friend friend) {
		this.friend = friend;
	}

	public Operation getOperation() {
		return operation;
	}

	public void setOperation(Operation operation) {
		this.operation = operation;
	}

	public String getChildElementXML() {
		StringBuffer xml = new StringBuffer();
		xml.append("<query xmlns=\"jabber:iq:friend\">");
		xml.append("<friends>");
		for (Friend friend : friends) {
			xml.append(createFriendNode(friend));
		}
		xml.append("</friends>");
		if (operation != null && !operation.equals("")) {
			xml.append("<operation>");
			xml.append(operation);
			xml.append("</operation>");
		}
		if (friend != null) {
			xml.append(createFriendNode(friend));
		}
		if (roleID != null) {
			xml.append("<roleID>");
			xml.append(roleID);
			xml.append("</roleID>");
		}
		if (friendGroupId != null) {
			xml.append("<friendGroupId>");
			xml.append(friendGroupId);
			xml.append("</friendGroupId>");
		}
		xml.append("</query>");
		return xml.toString().replaceAll("\\>\\s*|\t|\r|\n", ">");
	}

	/**
	 * 生成friendGroup节点
	 * 
	 * @param friend
	 * @return
	 */
	private String createFriendNode(Friend friend) {
		return "<friend>" + StringUtils.escapeNode(friend.toXML())
				+ ("</friend>");
	}
}
